/**
 * 使用方法  需要配合YipFile.php
 *var zip=new MC.Zip.Zblob();
 zip.open("./yipfile.json",filelist);//filelist 可以为空,
 * zip.Onload=function(url){	//加载完成的时候,调用,返回大文件的链接,zip.getUrl 可以获取子文件的链接
       $('#imgtest').attr('src',zip.getUrl("./js/image/bgImg/centerBg1.jpg"));
    };
	
 */
declare let filelist: any;
declare let te: any;
module MC {
	export module Zip {
		export class Zblob {
			public buffer: any;
			public constructor() {
			}
			/** 是否需要分割,读取文件结构信息,对文件进行分割 */
			public isFenge = false;
			/** 当前的进度 */
			public progress: number = 0;
			/** 是否加载完成 */
			public isComplete = false;
			/** 记录是否出现了错误 */
			public isError=false;
			private Connet(): XMLHttpRequest {
				if (this._connet) {
					return this._connet;
				}
				var g = null;
				if (XMLHttpRequest != undefined) {
					g = new XMLHttpRequest;
				} else {
					try {
						g = new ActiveXObject("MSXML2.XMLHTTP");
					} catch (f) {
						try {
							g = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (f) {
							g = null;
						}
					}
				}
				this._connet = g;
				return g;
			}
			/** 文件列表说明文件 */
			private _list: Array<any> = [];
			/** 用于搜索的数组 */
			private _namekeyList: any = []
			/** 创建的连接 */
			private _connet: XMLHttpRequest = null;
			public getList() {
				return this._list;
			}
			public OntimeProgress:Function=null;
			private url='';
			/** 打开一个连接 */
			public open(url: string, mime: string = null) {
				if(this.url===''){
					this.url=url;
				}
				debug.log('open:'+url);
				this.MIME = mime;
				let con = this.Connet();
				let self = this;
				con.open("get", url, true);
				con.addEventListener("error", (e: Event) => {
					self._handleErrorProxy(e);
					if(MC.OS.android){
						this.open(this.url+'?c='+Math.ceil(Math.random()*10));
					} 
				}, false);

				con.addEventListener("progress", (e: any) => {
					let total=3093924;
					if(e.total){
						total=e.total;
					}
					let progress=0;
				 	if(e.loaded&&total){
						 progress = parseFloat(<any>(e.loaded / total * 100).toFixed(2));
					}else{
						 progress = 0;
					} 
					if(progress>self.progress){
						self.progress=progress;
					}
					if(self.progress>100){
						self.progress=100;
					}
					this.OntimeProgress&&this.OntimeProgress();
				 
				}, false);
				let isload=false;
				con.addEventListener("load", (e: Event) => {
					if(isload){
						return;
					}
					self._handleLoadProxy(e);
					isload=true;
				}, false);
				con.responseType = 'arraybuffer';
				con.send();
			}


			private _handleErrorProxy(e: Event) {
				this.OnError();
			}
			private _handleLoadProxy(e: Event) {
				let connet: XMLHttpRequest = this.Connet();
				if (connet.readyState == 4) {
					if (connet.status == 200) {
						//	var message = connet.response;
						//	console.log(message);
						this._load();
					} else {
						this.OnError();
					}
				}
			}
			private MIME: string = null;
			/** 文件开始的位置 */
			private _beginSize = 0;
			private createBlob(): Blob {
				let connet: XMLHttpRequest = this.Connet();
				let obj: any = {};
				if (this.MIME) {
					obj.type = this.MIME;
				}
				/**{
					type: 'video/mp4'////'video/mp4'		///	'audio/mpeg'// 'text/html'
				} */
				///	obj.type='audio/mpeg';
				//	alert(obj.type);
				this.buffer = connet.response; 
				//	alert(d);
				return new Blob([connet.response], obj);
			}

			public _blob: Blob = null;
			private _load() {
				let mthis = this;
				this._blob = this.createBlob();
				let url = URL.createObjectURL(this._blob);
				
				if (!mthis.isFenge) {
					mthis.Onload(url);
					return;
				}
				this.fengeFile(() => {
					mthis.Onload(url);
				});
			}

			/** 加载完成时调用 参数为资源的url */
			public Onload(url: string) { }
			/** 分割文件 */
			private fengeFile(_fun: Function) {
				let mthis = this;
				if (!mthis._list) {
					return _fun();
				}
				var reader = new FileReader();
				reader.readAsArrayBuffer(this._blob);
				reader.onload = function (f: any) {
					///	console.log("读取成功,开始解析", f.target.result);
					mthis.aBuffer = f.target.result;
					te = mthis.aBuffer;
					let size8Array = new Uint8Array(mthis.aBuffer.slice(0, 4));
					if (size8Array.length !== 4) {
						console.log("读取文件失败,无效的拼接文件");
					}
					let sizeval = (size8Array[0] * 256 * 256 * 256)
						+ (size8Array[1] * 256 * 256)
						+ (size8Array[2] * 256)
						+ size8Array[3];

					mthis._beginSize = sizeval + 4;

					let reader = new FileReader();
					let newblob = new Blob([mthis.aBuffer.slice(4, sizeval + 4)]);
					reader.readAsBinaryString(newblob);
					reader.onload = function (evt: any) {
						mthis._list = JSON.parse(evt.target.result);////从文件中读取到文件说明,转换为数组
						mthis.zhengli(mthis._list);
						///	console.log(mthis._list);
						for (let one of mthis._list) {
							one.mime = mthis.getMIME(one);
							one.buffer = mthis.aBuffer.slice(mthis._beginSize + one.begin, mthis._beginSize + one.begin + one.size);
							//	alert('sssss');
							let nw: any = {};
							nw.blob = new Blob([one.buffer], {
								type: one.mime// 'audio/mpeg'////'video/mp4'		///	'audio/mpeg'// 'text/html'
							});
							nw.url = URL.createObjectURL(nw.blob);
							nw.mime = one.mime;
							nw.buffer = one.buffer;
							nw.id = one.id;
							mthis._namekeyList[one.id] = nw;
						}
						_fun();
					}
				};
			}
			private aBuffer: ArrayBuffer = null;
			/** 根据文件名返回链接 */
			public getUrl(id: string) {
				if (typeof (this._namekeyList[id]) == 'object') {
					return this._namekeyList[id].url;
				} else {
					console.log("获取无效文件id:" + id);
					this.OnError();
				}
			}
			/** 返回图片 */
			public getImg(id: string) {
				if (typeof (this._namekeyList[id]) == 'object') {
					return this._namekeyList[id].img;
				} else {
					console.log("获取无效文件id:" + id);
					this.OnError();
				}
			}
			/** 返回Buffer */
			public getBuffer(id: string) {
				if (typeof (this._namekeyList[id]) == 'object') {
					return this._namekeyList[id].buffer;
				} else {
					console.log("获取无效文件id:" + id);
					this.OnError();
				}
			}


			public getNodeObj(id: string) {
				if (typeof (this._namekeyList[id]) == 'object') {
					return this._namekeyList[id];
				} else {
					console.log("获取无效文件id:" + id);
					this.OnError();
				}
			}


			public OnError() {

			}


			/*** 读取加载的文件 */
			public ReadImgs(fun: Function) {
				let _isfun = false;
				let mthis = this;
				//	console.log(this._namekeyList, this._list);
				let imgcount = 0;
				for (let one of this._list) {
					if (one.mime&&one.mime.indexOf('image') >= 0) {
						imgcount++;
					}
				}
				let count = imgcount;
				for (let one of this._list) {
					let obj = this._namekeyList[one.id];
					if (obj && obj.blob.type.indexOf('image') >= 0) {
						let img = new Image;
						img.src = obj.url;
						obj.img = img;
						img.onload = () => {
							count--;
							if (count <= 0) {
								if (_isfun) {
									return;
								}
								_isfun = true;
								mthis.isComplete = true;
								return fun();
							}
						};
					} else {
						count--;
						if (count <= 0) {
							if (_isfun) {
								return;
							}
							_isfun = true;
							mthis.isComplete = true;
							return fun();
						}
					}
				}
				setTimeout(function () {
					if (_isfun) {
						return;
					}
				//	_isfun = true;
					fun();
				}, 1000);
			}



			/**
			 * 分析出类型
			 */
			private getMIME(one: any): string {
				if (one.mime) {
					return one.mime;
				}
				///'audio/mpeg'////'video/mp4'		///	'audio/mpeg'// 'text/html'
				let str = one.src.toLowerCase();
				let type = str.replace(/^.+\./, '');
				if (type == 'mp4') {
					one.mime = 'video/mp4';
				} else if (type == 'mp3' || type == 'ogg') {
					one.mime = 'audio/mpeg';
				} else if (type == 'jpg') {
					one.mime = 'image/jpeg';
				} else if (type == 'png') {
					one.mime = 'image/png';
				}
				return one.mime;
			}

			/** 对数组进行整理 */
			private zhengli(list: Array<any>) {
				let begin = 0;
				for (let one of list) {
					one.begin = begin;
					begin += one.s;
					one.size = one.s;
					one.id = one.i;
				}
			}

		}
	}
}